<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleslist" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              class="ven_tent"
              :gutter="20"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['dbBottom', i1 === 0 ? 'dbTop' : '']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  style="margin-left: 20px"
                  closable
                  @close="colsableById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  class="ven_tent"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'dbTop']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="colsableById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      @close="colsableById(scope.row, item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row.children }}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger "
              icon="el-icon-delete"
              @click="deleteRoles(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning "
              icon="el-icon-setting"
              @click="showDialog(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setDialogVisible"
      width="50%"
      @close="clearArr"
    >
      <!-- 树形控件区域 -->
      <el-tree
        :data="showDialogList"
        :props="treeRoles"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allolDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <el-form ref="addFormRef" :model="addForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <!-- 添加角色的对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormRef" :model="editForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesBtn(editForm.roleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleslist: [],
      // 控制分配权限对话框的显示隐藏
      setDialogVisible: false,
      // 分配权限数组
      showDialogList: [],
      // 树形控件数据
      treeRoles: {
        label: 'authName',
        childern: 'childern'
      },
      // 默认选中已选中节点属性的数组
      defKeys: [],
      // 添加用户对话框的显示隐藏
      addDialogVisible: false,
      // 添加用户
      addForm: {},
      // 编辑用户
      editForm: {},
      // 编辑用户对话框的显示隐藏
      editDialogVisible: false,
      // 角色的id
      roleId: ''
    }
  },
  created() {
    // 获取角色列表
    this.getRolesList()
  },
  mounted() {},
  methods: {
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleslist = res.data
    },
    // 删除权限小标签
    async colsableById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      // 调接口
      const { data: res } = await this.$axios.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      // 不能重新渲染页面会合住
      // this.getRolesList()
      role.children = res.data
    },
    // 获取所有的分配权限
    async showDialog(role) {
      const { data: res } = await this.$axios.get('rights/tree')
      console.log(role)
      this.roleId = role.id
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.showDialogList = res.data

      //调取递归函数把值传进 defKeys 数组中
      this.getLeafKeys(role, this.defKeys)
      this.setDialogVisible = true
    },
    // 通过递归的形式，获取所有三级权限的id
    getLeafKeys(node, arr) {
      //如果当前 node节点不包含 children，说明是三级权限
      if (!node.children) return arr.push(node.id)
      //不满足if条件执行一下代码
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 添加角色
    addRoles() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$axios.post('roles', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    async deleteRoles(delId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.error('删除角色失败！')
      }
      //调接口删除角色
      const { data: res } = await this.$axios.delete('roles/' + delId.id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败！')
      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    // 获取编辑角色数据
    async editRoles(editId) {
      this.editDialogVisible = true
      const { data: res } = await this.$axios.get('roles/' + editId.id)
      console.log(res)
      if (res.meta.status !== 200) return
      this.editForm = res.data
    },
    editRolesBtn(id) {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        console.log(id)
        const { data: res } = await this.$axios.put(
          'roles/' + id,
          this.editForm
        )
        if (res.meta.status !== 200)
          return this.$message.error('编辑用户失败！')
        this.$message.success('编辑用户成功！')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    clearArr() {
      this.defKeys = []
    },
    // 分配角色里的确定按钮
    async allolDialog() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const strId = keys.join(',')
      const { data: res } = await this.$axios.post(
        `roles/${this.roleId}/rights`,
        { rids: strId }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.info('分配角色失败')
      this.$message.success('分配角色成功')
      this.getRolesList()
      this.setDialogVisible = false
    }
  }
}
</script>

<style scoped >
.el-tag {
  margin: 10px;
}
.dbTop {
  border-top: 1px solid #eee;
}
.dbBottom {
  border-bottom: 1px solid #eee;
}
.ven_tent {
  display: flex;
  align-items: center;
}
</style>
